#!/bin/sh

. /usr/share/common

ensure_command "openRTSP"
ensure_command "jct"

SELF_NAME="$(basename "$0")"
STREAMER_APP="prudynt"
STREAMER_CONF_FILE="/etc/prudynt.json"

# "parameter" "default"
read_config() {
	jct "$STREAMER_CONF_FILE" get "$1"
	[ -z "$_" ] || echo "$2"
}

stream_number=1
stream_endpoint=$(read_config stream${stream_number}.rtsp_endpoint ch1)
rtsp_stream="rtsp://127.0.0.1/$stream_endpoint"

vformat="-4"
record_videofmt="mp4"
record_duration=10

CLIP_FILE="/tmp/vbuffer.${record_videofmt}"
LOCK_FILE="/tmp/vbuffer.lock"
TEMP_FILE="/tmp/vbuffer.tmp"

if ! is_streamer_running; then
	echo_error "Streamer is not running"
	exit 1
fi

if is_streamer_disabled; then
	echo_error "Streamer disabled"
	exit 1
fi

start() {
	echo_title "Starting video buffer"

	if pidof -o $$ $SELF_NAME > /dev/null; then
		echo_error "is already running"
		exit 1
	fi

	rtsp_username=$(read_config rtsp.username thingino)
	rtsp_password=$(read_config rtsp.password thingino)
	stream_width=$(read_config stream${stream_number}.width 640)
	stream_height=$(read_config stream${stream_number}.height 360)
	stream_fps=$(read_config stream${stream_number}.fps 25)

	while : ; do
		openRTSP -V -u $rtsp_username $rtsp_password \
			-w $stream_width -h $stream_height -f $stream_fps \
			-d $record_duration $vformat \
			-t $rtsp_stream > "$TEMP_FILE" \
			2>/dev/null
		while [ -f "$LOCK_FILE" ]; do
			age=$(( $(date +%s) - $(date +%s -r "$LOCK_FILE") ))
			if [ "$age" -gt 100 ]; then
				echo_info "Lock file is expired"
				rm -f "$LOCK_FILE"
			fi
			echo -n "."
			sleep 1
		done
		mv -f "$TEMP_FILE" "$CLIP_FILE"
	done &
}

# FIXME: $0 does not work here
stop() {
	echo_title "Stopping video buffer"

	pid=$(pidof -o %PPID -s $SELF_NAME)
	if [ -z "$pid" ]; then
		echo_info "Nothing to stop"
	else
		while [ -n "$pid" ]; do
			kill -9 $pid > /dev/null
			pid=$(pidof -o %PPID -s $SELF_NAME)
		done
	fi

	if [ -f "$CLIP_FILE" ]; then
		rm -f "$CLIP_FILE"
	fi

	if [ -f "$LOCK_FILE" ]; then
		rm -f "$LOCK_FILE"
	fi

	if [ -f "$TEMP_FILE" ]; then
		sleep $record_duration
		rm "$TEMP_FILE"
	fi
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop || true
		sleep 1
		start
		;;
	*)
		usage "{start|stop|restart}"
		;;
esac

exit 0
